using System;
using Metro.SmartClient.Infrastructure.Interface.Services;
using Metro.Admin.BusinessEntities;
using Microsoft.Practices.CompositeUI.Services;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.SmartClient.DisconnectedAgent;
using Microsoft.Practices.SmartClient.ConnectionMonitor;
using Microsoft.Practices.SmartClient.EnterpriseLibrary;
using Metro.SmartClient.Infrastructure.Interface.Constants;
using Microsoft.Practices.CompositeUI.EventBroker;
using Metro.SmartClient.Infrastructure.Interface;
using Microsoft.Practices.CompositeUI.Commands;

namespace Metro.SmartClient.Infrastructure.Library.Services
{
	public class UserSelectorService : IUserSelectorService
	{
        private WorkItem localWorkitem;
        private IConnectionMonitor connectionMonitor;
        [EventPublication(EventTopicNames.OnlineStatusUpdate, PublicationScope.Global)]
        public event EventHandler<EventArgs<string>> OnlineStatus;

        public UserSelectorService([ServiceDependency] WorkItem workItem)
		{
            this.localWorkitem = workItem;
            this.AddServices();
		}

        [ServiceDependency]
        public WorkItem WorkItem
        {
            get { return localWorkitem; }
            set { localWorkitem = value; }
        }

        public User SelectUser()
		{
            Login form = new Login(this.localWorkitem);
			return form.SelectUser();
		}

        private void AddServices()
        {

            try
            {
                RequestManager requestManager = DatabaseRequestManagerIntializer.Initialize();
                requestManager.StartAutomaticDispatch();
 
                connectionMonitor = requestManager.ConnectionMonitor;
                connectionMonitor.ConnectionStatusChanged += new EventHandler(connectionMonitor_ConnectionStatusChanged);

                UpdateConnectivityStatusLabel(connectionMonitor.IsConnected);
                WorkItem.Services.Add(requestManager.RequestQueue);
                WorkItem.RootWorkItem.Services.Add(connectionMonitor);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void connectionMonitor_ConnectionStatusChanged(object sender, EventArgs e)
        {
            UpdateConnectivityStatusLabel(connectionMonitor.IsConnected);
        }

        private void UpdateConnectivityStatusLabel(bool connected)
        {
            string status = connected ? "online" : "offline";
            OnOnlineStatus(new EventArgs<string>(status));
        }

        protected virtual void OnOnlineStatus(EventArgs<string> eventArgs)
        {
            if (OnlineStatus != null)
            {
                OnlineStatus(this, eventArgs);
            }
        }
	}
}
